package cn.xuqiudong.sso.server.service.impl;

import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.util.encrypt.PasswordUtils;
import cn.xuqiudong.sso.common.model.SsoUser;
import cn.xuqiudong.sso.server.service.SsoUserService;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 描述:
 *
 * @author Vic.xu
 * @since 2021-10-29 17:47
 */
@Service
public class SsoUserServiceImpl implements SsoUserService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public BaseResponse<SsoUser> login(String group, String username, String password) {
        SsoUser user = findUserByUsername(group, username);
        if (user == null) {
            return BaseResponse.error(String.format("User %s not found in group %s", username, group));
        }

        boolean validatePassword = PasswordUtils.validatePassword(password, user.getPassword());
        if (!validatePassword) {
            return BaseResponse.error("用户名或密码错误");
        }
        return BaseResponse.success(user);
    }

    public SsoUser findUserByUsername(String group, String username) {
        String sql = "SELECT a.id, a.username, a.password, a.group  FROM sso_user a WHERE a.username = ? and a.group = ?  LIMIT 1 ";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<SsoUser>(SsoUser.class), username, group);
        } catch (Exception e) {
            return null;
        }

    }
}
